package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dto.CreateOrderRequest;
import com.cskaoyan.order.dto.CreateOrderResponse;
import com.cskaoyan.order.dto.OrderListRequest;
import com.cskaoyan.order.dto.OrderListResponse;
import com.cskaoyan.order.form.PageInfo;
import com.cskaoyan.order.service.impl.OrderCoreServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/20
 * @TIME: 10:07
 * @PROJECT_NAME: duolaimall
 */
@RestController
@RequestMapping("shopping")
public class OrderController {

    @Autowired
    OrderCoreServiceImpl orderCoreService;

    /**
     * @Description: 创建订单
     * @Author: cuiweiguo#
     * @Date: 2022/5/20 10:08
     * @Param: :
     * @return: :
     **/
    //@PostMapping("order")
    public ResponseData postOrder(@RequestBody CreateOrderRequest orderRequest, HttpServletRequest request) {
        //从header中获得用户信息
        String userInfo = (String) request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Integer uid = Integer.parseInt(object.get("uuid").toString());
        orderRequest.setUserId(uid.longValue());
        //设置unitkey
        orderRequest.setUniqueKey(UUID.randomUUID().toString());
        //创建订单业务
        CreateOrderResponse response = orderCoreService.createOrder(orderRequest);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getOrderId(),"success");
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * @Description: 显示用户所有订单
     * @Author: cuiweiguo#
     * @Date: 2022/5/20 16:58
     * @Param: :
     * @return: :
     **/
    //@GetMapping("order")
    public ResponseData getOrder(OrderListRequest orderListRequest, HttpServletRequest request) {
        //http://localhost:9999/shopping/order?size=5&page=1
        //从header中获得用户信息
        String userInfo = (String) request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Integer uid = Integer.parseInt(object.get("uuid").toString());
        //根据用户的id查询用户的订单
        orderListRequest.setUserId(uid.longValue());
        OrderListResponse orderListResponse = orderCoreService.queryOrdersByUserId(orderListRequest);
        return new ResponseUtil<>().setData(orderListResponse,"success");
    }

}
